<?php namespace App\Admin\Access\User;

use Auth, Route;
use App\Core\Model as BaseModel;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use App\Admin\Access\Operation\Model as Operation;
use App\Admin\Access\OperationGroup\Model as OperationGroup;

class Model extends BaseModel implements AuthenticatableContract {
    
    use Authenticatable;

    protected $table = 'sys_user';
    protected $primaryKey = 'user_id';
    
    protected $hidden = array('password', 'saltcode', 'remember_token');
    
    private $adminId = '60';
	
	private $managerIds = ['359', '333'];
	
	public function role(){
		return $this->belongsTo('App\Admin\Access\Role\Model', 'role_id', 'role_id');
	}
    
    public function supplier(){
        return $this->belongsTo('App\Admin\Supplier\Supplier\Model', 'user_id', 'admin_id');
    }
    
    public function agent(){
        return $this->belongsTo('App\Admin\Seller\Agent\Model', 'user_id', 'admin_id');
    }
    
    public function agents(){
        return $this->hasMany('App\Admin\Seller\Agent\Model', 'seller_id', 'user_id');
    }
    
    public function seller(){
        return $this->belongsTo('App\Admin\Seller\Seller\Model', 'user_id', 'admin_id');
    }
    
    //-------------------------------------------------------公共业务---------------------------------------------------------
	
	//验证用户权限
	public function hasPermission($action = ''){
		if($this->isAdmin()){
			return true;
		}
		//拥有的权限
		static $myOperations = '';
		if(!$myOperations){
			$user = Auth::user();
			if($user && $user->role){
				$myOperations = $user->role->operation_ids;
			}
		}
		if(!$myOperations){
			return false;
		}
		$action = $action == '' ? Route::currentRouteAction() : $action;
        $action = str_replace('App\\Http\\Controllers\\', '', $action);
		if(is_numeric($action)){//操作ID？
			$operationId = $action;
		}else{//操作码
			$operation = Operation::where('code', '=', $action)->first();
			if(!$operation){
				return false;
			}
			$operationId = $operation->id;
		}
		return strpos(','.$myOperations.',', ','.$operationId.',') !== false;
	}
	
	//判断用户是否拥有指定组的权限,可以提供多个分组ID，如果为多个ID，则其中任何一个满足都返回true
	public function hasGroup($group){
		if($this->isAdmin()){
			return true;
		}
		static $myGroups = array();
		if(!$myGroups){//初始化所有操作分组
			$user = Auth::user();
			if(!$user || !$user->role){
				return false;
			}
			$operationsStr = $user->role->operation_ids;
			if($operationsStr){
				if(strpos($operationsStr, ',') !== false){
					$operationsArr = explode(',', $operationsStr);
				}else{
					$operationsArr = array($operationsStr);
				}
				$operationModel = new Operation();
				$operations = $operationModel->distinct()->select('group_id')->whereIn('id', $operationsArr)->get();
				foreach ($operations as $value){
					$myGroups[] = $value->group_id;
				}
			}
		}
		$flag = false;
		$groups = is_array($group) ? $group : func_get_args();
		foreach ($groups as $value){
			if(in_array($value, $myGroups)){
				$flag = true;
			}
		}
		return $flag;
	}

	//判断用户是否拥有某个角色
	public function hasRole($roleId){
		static $res = '';
		if($res !== ''){//初始化所有操作分组
			$user = Auth::user();
			if(!$user || !$user->role){
				$res = false;
			}
			$res = $user->role->role_id == $roleId;
		}
		return $res;
	}
	
	//返回当前用户是否是超级管理员
	public function isAdmin(){
		return $this->user_id == $this->adminId;
	}
	
	//返回当前用户是否是管理员
	public function isManager(){
		static $isManager = false;
		static $isChecked = false;
		if(!$isChecked){
			if(in_array($this->user_id, $this->managerIds) || $this->role->is_manager == '1'){
				$isManager = true;
			}
			$isChecked = true;
		}
		return $isManager;
	}
	
	//返回超级管理员Id
	public function getAdminId(){
		return $this->adminId;
	}
	
	//返回用户角色名称
	public function getFullRoleName($seperator = "-"){
		if($this->isAdmin()){
			return '超级管理员';
		}
		if($this->role){
			$user = Auth::user();
			if($user->isAdmin()){
				return $this->role->getFullName('', $seperator);
			}
			if($this->role->role_id == $user->role->role_id){
				return $this->role->name;
			}
			return $this->role->getFullName($user->role->role_id, $seperator);
		}
		return '';
	}
	
	//返回用户角色名称
	public function getRoleName(){
		if($this->isAdmin()){
			return '超级管理员';
		}
		if($this->role){
			return $this->role->name;
		}
		return '';
	}
	
	//当前用户拥有的操作
	public function getOperations(){
		static $operations = [];
		if(!$operations){
			if($this->isAdmin()){
				$operations = with(new Operation())->all();
			}elseif($this->role){
                $ids = $this->role->getOperationIds();
                $operations = $ids ? with(new Operation())->whereIn('id', $ids)->get() : [];
			}
		}
		return $operations;
	}
	
	//获取当前用户的所有操作组
	public function getOperationGroups(){
		static $groups = [];
		if(!$groups){
			if($this->isAdmin()){
				$groups = with(new OperationGroup())->all();
			}else{
				$operations = $this->getOperations();
				$groupIds = [];
				foreach($operations as $operation){
					if(is_numeric($operation->group_id)){
						$groupIds[] = $operation->group_id;
					}
				}
				$groups = with(new OperationGroup())->whereIn('group_id', $groupIds)->get();
			}
		}
		return $groups;
	}
}